﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

namespace Common
{
    /// <summary>
    /// Json操作、Json对象类
    /// </summary>
    [Serializable]
    [DataContract]
    public class JsonTool
    {
        #region 数据集（列表）对象PagerJsonData
        /// <summary>
        /// 数据集（列表）对象
        /// </summary>
        [Serializable]
        [DataContract(Name = "PagerJsonData_Using_{0}", Namespace = "Matrix.Common.Utility.JsonTools")]
        public class PagerJsonData<T>
        {
            public PagerJsonData(List<T> rowList, int rowCount)
            {
                rows = rowList;
                total = rowCount;
            }
            /// <summary>
            /// 数据集List
            /// </summary>
            [DataMember(Name = "rows")]
     
            public List<T> rows { get; set; }

            /// <summary>
            /// 数据总条数
            /// </summary>
            [DataMember(Name = "total")]
   
            public int total { get; set; }
        }
        #endregion

        [Serializable]
        [DataContract(Name = "IPagerJsonData_Using_{0}", Namespace = "Matrix.Common.Utility.JsonTools")]
        public class IPagerJsonData<T>
        {
            public IPagerJsonData(List<T> rowList, int rowCount, int pIndex, int pSize)
            {
                rows = rowList;
                total = rowCount;
                pageIndex = pIndex;
                pageSize = pSize;
            }

            public IPagerJsonData(List<T> rowList, int rowCount, int pIndex, int pSize, int nPages)
            {
                rows = rowList;
                total = rowCount;
                pageIndex = pIndex;
                pageSize = pSize;
                pages = nPages;
            }

            /// <summary>
            /// 数据集List
            /// </summary>
            [DataMember(Name = "rows")]
    
            public List<T> rows { get; set; }

            /// <summary>
            /// 数据总条数
            /// </summary>
            [DataMember(Name = "total")]
         
            public int total { get; set; }

            /// <summary>
            /// 当前页数
            /// </summary>
            [DataMember(Name = "pageIndex")]
         
            public int pageIndex { get; set; }

            /// <summary>
            /// 当前页总条数
            /// </summary>
            [DataMember(Name = "pageSize")]
    
            public int pageSize { get; set; }

            /// <summary>
            /// 当前页总条数
            /// </summary>
            [DataMember(Name = "pages")]
     
            public int pages { get; set; }
        }

        #region 执行操作成功与否Json

        [Serializable]
        [DataContract(Name = "DoResult_Using_{0}", Namespace = "Matrix.Common.Utility.JsonTools")]
        public class DoResult<T>
        {
            /// <summary>
            /// 执行成功与否
            /// </summary>
            [DataMember(Name = "result")]
       
            public bool result { get; set; }

            /// <summary>
            /// 返回内容
            /// </summary>
            [DataMember(Name = "msg")]
     
            public string msg { get; set; }

            /// <summary>
            /// 返回对象
            /// </summary>
            [DataMember(Name = "obj")]
      
            public T obj { get; set; }
        }

        [Serializable]
        [DataContract(Name = "DoResultSimple_Using_{0}", Namespace = "Matrix.Common.Utility.JsonTools")]
        public class DoResultSimple
        {
            /// <summary>
            /// 执行成功与否
            /// </summary>
            [DataMember(Name = "result")]
    
            public bool result { get; set; }
            /// <summary>
            /// 返回内容
            /// </summary>
            [DataMember(Name = "msg")]
 
            public string msg { get; set; }
        }

        [Serializable]
        [DataContract(Name = "DoResultAd_Using_{0}", Namespace = "Matrix.Common.Utility.JsonTools")]
        public class DoResultAd
        {
            /// <summary>
            /// 执行成功与否
            /// </summary>
            [DataMember(Name = "result")]

            public int result { get; set; }
            /// <summary>
            /// 返回内容
            /// </summary>
            [DataMember(Name = "msg")]
    
            public string msg { get; set; }
        }




        #endregion

        #region Json和对象的转换

        /// <summary>
        /// 转换List<T>的数据为JSON格式
        /// </summary>
        /// <typeparam name="T">类</typeparam>
        /// <param name="vals">列表值</param>
        /// <returns>JSON格式数据</returns>
        public static string TOJSON<T>(List<T> vals)
        {
            System.Text.StringBuilder st = new System.Text.StringBuilder();
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));

                foreach (T city in vals)
                {
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        s.WriteObject(ms, city);
                        st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return st.ToString();
        }

        /// <summary>
        /// 将对象转换为Json
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ObjToJson(object value)
        {
            Type type = value.GetType();
            var json = new Newtonsoft.Json.JsonSerializer
            {
                NullValueHandling = NullValueHandling.Ignore,
                ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace,
                MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            var sw = new System.IO.StringWriter();
            var writer = new JsonTextWriter(sw) { Formatting = Formatting.None, QuoteChar = '"' };
            json.Serialize(writer, value);
            string output = sw.ToString();
            writer.Close();
            sw.Close();
            return output;
        }

        /// <summary>
        /// 将Json字符串转换为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonText"></param>
        /// <returns></returns>
        public static T JsonToObj<T>(string jsonText)
        {
            var json = new Newtonsoft.Json.JsonSerializer
            {
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace,
                MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore,
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            };
            var sr = new System.IO.StringReader(jsonText);
            var reader = new JsonTextReader(sr);
            T result = (T)json.Deserialize(reader, typeof(T));
            reader.Close();
            return result;
        }
        #endregion
    }
}
